package br.com.academia.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.academia.dao.UsuarioDAO;
import br.com.academia.modelo.Usuario;

public class Login extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private HttpSession session;

	public Login() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String senha = request.getParameter("senha");

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		Usuario usuario = new Usuario();
		usuario.setLogin(login);
		usuario.setSenha(senha);

		UsuarioDAO dao = new UsuarioDAO();

		if (dao.logar(usuario)) {
			session = request.getSession();
			session.setAttribute("usuario", usuario);

			out.print("<script language='javascript'>");
			out.print("location.href='index.jsp'");
			out.print("</script>");
		} else {
			out.print("<script language='javascript'>");
			out.print("alert('Usuario ou senha incorreto!');");
			out.print("history.back();");
			out.print("</script>");
		}
	}

}
